import axios from 'axios'
import store from '@/store'
import router from '@/router'

const instance = axios.create({
	baseURL: 'https://apipc-xiaotuxian-front.itheima.net'
})

// 请求拦截器
instance.interceptors.request.use(config => {
	const { token } = store.state.user.profile
	if (token) {
		config.headers.Authorization = `Bearer ${token}`
	}
	return config
}, error => {
	return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response => {
	const { result } = response.data
	return result
}, error => {
	if (error.response.status === 401) {
		// vue3要加value获取当前页面地址
		const redirectUrl = router.currentRoute.value.fullPath
		router.push(`/login?redirectUrl=${redirectUrl}`)
	}

	return Promise.reject(error)
})

const request = (url, method, data) => {
	return instance({
		url,
		method,
		[method.toLowerCase() === 'get' ? 'params' : 'data']: data
	})
}

export default request
